<template>
  <a-modal
    destroyOnClose
    :visible="visible"
    :title="title"
    @update:visible="update"
    @ok="ok"
  >
    <Form ref="formRef" v-model:form="form" :formList="formList" :btnConfig="null">
      <template #parent_id>
        <a-select
          v-model:value="form.parent_id"
          style="width: 100%"
          placeholder="请选择字典类型"
        >
          <a-select-option v-for="item in dictList" :key="item.id" :value="item.id">
            <span>{{ item.title }}</span>
          </a-select-option>
        </a-select>
      </template>
    </Form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, defineProps, toRefs, defineEmits, watch, onMounted } from "vue";
import Form from "@/components/Form";
import { formList } from "./href";
import { dictApi } from "@/api/dict";

const emits = defineEmits(["update:visible", "reload"]);
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  tempData: {
    default: {},
  },
});
const { visible, tempData } = toRefs(props);
const title = ref("提示");
const formRef = ref();
const form = ref({});

const dictList = ref([]);

watch(visible, (e) => {
  if (!e) return;
  const { id } = tempData.value;
  if (id) title.value = "修改字典";
  else title.value = "新增字典";
  form.value = tempData.value;
  getTree();
});

async function getTree(page = 1) {
  const result = await dictApi.page({
    page_size: 10,
    current_page: page,
  });
  const { list } = result;
  dictList.value = list.map((i) => {
    delete i.children;
    return i;
  });
}

function update(e) {
  emits("update:visible", e);
}
async function ok() {
  await formRef.value.save();
  await dictApi.edit(form.value);
  emits("update:visible", false);
  emits("reload");
}
</script>

<style lang="less" scoped></style>
